#!/bin/bash

# 设置错误时退出
set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

# 打印带颜色的信息
print_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

print_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查命令是否存在
check_command() {
    if ! command -v $1 &> /dev/null; then
        print_error "$1 未安装"
        exit 1
    fi
}

# 检查环境
check_environment() {
    print_info "检查环境..."
    
    # 检查Python
    check_command python3
    check_command pip3
    
    # 检查Node.js
    check_command node
    check_command npm
    
    # 检查Docker
    check_command docker
    check_command docker-compose
    
    print_info "环境检查完成"
}

# 安装依赖
install_dependencies() {
    print_info "安装依赖..."
    
    # 安装Python依赖
    pip3 install -r requirements.txt
    
    # 安装开发依赖
    pip3 install -r requirements-dev.txt
    
    print_info "依赖安装完成"
}

# 运行测试
run_tests() {
    print_info "运行测试..."
    
    # 运行Python测试
    pytest --cov=video_agent --cov-report=term-missing
    
    print_info "测试完成"
}

# 构建前端
build_frontend() {
    print_info "构建前端..."
    
    # 安装前端依赖
    npm install
    
    # 构建前端
    npm run build
    
    print_info "前端构建完成"
}

# 启动监控
start_monitoring() {
    print_info "启动监控系统..."
    
    # 启动Prometheus和Grafana
    cd monitoring
    docker-compose up -d
    cd ..
    
    print_info "监控系统启动完成"
}

# 启动应用
start_application() {
    print_info "启动应用..."
    
    # 启动FastAPI应用
    uvicorn api_server:app --host 0.0.0.0 --port 8000 --reload
    
    print_info "应用启动完成"
}

# 主函数
main() {
    print_info "开始部署..."
    
    # 检查环境
    check_environment
    
    # 安装依赖
    install_dependencies
    
    # 运行测试
    run_tests
    
    # 构建前端
    build_frontend
    
    # 启动监控
    start_monitoring
    
    # 启动应用
    start_application
    
    print_info "部署完成"
}

# 执行主函数
main 